﻿using Fonour.Application.Services.Interfaces;
using Fonour.MVC.Models;
using Fonour.Utility;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;

namespace Fonour.MVC.Controllers
{
    [Authorize]
    public class LoginController : Controller
    {
        IUserAppService _userAppService;

        public LoginController(IUserAppService userAppService)
        {
            this._userAppService = userAppService;
        }

        [HttpGet]
        [AllowAnonymous]
        public IActionResult Index()
        {
            HttpContext.Request.Cookies.TryGetValue("UserName", out string cookieUserName);

            string loginUserName = string.Empty;
            var loginUser = HttpContext.User;
            if (loginUser.Claims.Any(p => p.Type == ClaimTypes.Name))
            {
                loginUserName = loginUser.Claims.FirstOrDefault(p => p.Type == ClaimTypes.Name).Value;
            }

            if (!string.IsNullOrEmpty(loginUserName))
            {
                return RedirectToAction("Index", "Home");
            }

            if (!string.IsNullOrEmpty(cookieUserName))
            {
                LoginModel model = new LoginModel()
                {
                    RememberMe = true,
                    UserName = cookieUserName
                };
                return View(model);
            }

            return View();

        }

        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous]
        public async Task<IActionResult> Index(LoginModel model)
        {
            if (ModelState.IsValid)
            {
                var user = await _userAppService.CheckUserAsync(model.UserName, model.Password);
                if (user != null)
                {
                    var claims = new List<Claim>
                    {
                        new Claim(ClaimTypes.Name, model.UserName),
                        new Claim(ClaimTypes.Sid, user.Id.ToString())
                    };
                    ClaimsPrincipal principal = new ClaimsPrincipal(new ClaimsIdentity(claims, "login"));
                    await HttpContext.SignInAsync(
                                                    CookieAuthenticationDefaults.AuthenticationScheme,
                                                    principal,
                                                    new AuthenticationProperties()
                                                    {
                                                        AllowRefresh = false,
                                                        ExpiresUtc = DateTimeOffset.UtcNow.AddHours(1),
                                                        IsPersistent = model.RememberMe
                                                    });
                    if (model.RememberMe)
                    {
                        HttpContext.Response.Cookies.Append("UserName", model.UserName);
                    }

                    // 记录Session
                    HttpContext.Session.Set("CurrentUserId", ByteConvertHelper.Object2Bytes(user.Id));
                    HttpContext.Session.Set("CurrentUser", ByteConvertHelper.Object2Bytes(user));
                    return RedirectToAction("Index", "Home");
                }

                ModelState.AddModelError(string.Empty, "用户名密码错误");
                return this.View();
            }

            return View(model);
        }

        /// <summary>
        /// 注销
        /// </summary>
        [HttpPost]
        public async Task<IActionResult> Logout()
        {
            // 注销登录的用户，相当于ASP.NET中的FormsAuthentication.SignOut  
            await HttpContext.SignOutAsync();
            HttpContext.Response.Cookies.Delete("UserName");
            return RedirectToAction("Index", "Login");
        }
    }
}
